<template>
  <div class="av-canvas-container">
    <div class="content-wrapper">
      <div class="canvas-wrapper" ref="canvasContainerRef"></div>
      
      <!-- 右侧 transformData 数据展示面板 -->
      <div class="transform-data-panel">
        <h4>变换数据</h4>
        <el-descriptions border direction="vertical" :column="1" size="small">
          <el-descriptions-item label="旋转角度 (angle)">
            {{ transformData.angle || '0.000' }}°
          </el-descriptions-item>
          <el-descriptions-item label="X 坐标">
            {{ transformData.x || '0' }}
          </el-descriptions-item>
          <el-descriptions-item label="Y 坐标">
            {{ transformData.y || '0' }}
          </el-descriptions-item>
          <el-descriptions-item label="宽度 (w)">
            {{ transformData.w || '0' }}
          </el-descriptions-item>
          <el-descriptions-item label="高度 (h)">
            {{ transformData.h || '0' }}
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="data-actions">
          <el-button size="small" type="primary" @click="resetTransform">
            重置变换
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue';
import { ElMessage, ElDescriptions, ElDescriptionsItem, ElDialog, ElPopconfirm, ElMessageBox } from 'element-plus';
import { AVCanvas } from '@webav/av-canvas';
import { ImgClip, VisibleSprite, MP4Clip } from '@webav/av-cliper';

const props = defineProps({
  iconData: {
    type: Object,
    default: () => ({})
  },
  iconType: {
    type: String,
    default: 'team'
  }
});

// 状态变量
const canvasContainerRef = ref(null);
const canvas = ref(null);
const activeSprite = ref(null); // 当前活动的精灵
const transformData = ref({ angle: 0 });
const initTransformData = {};

// 初始化画布
const initCanvas = async () => {
  if (!canvasContainerRef.value) {
    console.error('Canvas container not found');
    return;
  }
  
  try {
    // 如果已存在实例，先销毁
    if (canvas.value) {
      canvas.value.destroy();
      canvas.value = null;
    }

    // 创建 AVCanvas 实例
    canvas.value = new AVCanvas(canvasContainerRef.value, {
      bgColor: '#333',
      width: 1080,
      height: 1920,
    });
    
    console.log('Canvas initialized');
    
    // 如果有图标数据，加载图标
    if (props.iconData && props.iconData.url) {
      await loadIcon(props.iconData.url);
    } else if (props.iconData && props.iconData.file_path) {
      await loadIcon(props.iconData.file_path);
    }
  } catch (error) {
    console.error('初始化画布失败:', error);
    ElMessage.error(`初始化画布失败: ${error.message || '未知错误'}`);
  }
};

// 加载图标
const loadIcon = async (url) => {
  if (!canvas.value) return;
  
  try {
    console.log('Loading icon:', url);
    
    // 从URL加载媒体
    const response = await fetch(url);
    const blob = await response.blob();
    const clip = await createImageClip(blob);

    
    // 创建可见精灵并添加到画布
    const sprite = new VisibleSprite(clip);
    sprite.on('propsChange', (changedProps) => {

        const { angle, x, y, h, w } = changedProps.rect
        const floatNumber = 3
        transformData.value = {
          angle: angle?.toFixed(floatNumber) || transformData.value.angle,
          x : x?.toFixed(floatNumber) || transformData.value.x,
          y : y?.toFixed(floatNumber) || transformData.value.y,
          h : h?.toFixed(floatNumber) || transformData.value.h,
          w : w?.toFixed(floatNumber) || transformData.value.w,
        };
        if (transformData.value.w === 0 && transformData.value.h === 0) {
          // 初始化时设置宽高
          initTransformData.value = transformData.value
        }
    });

    await canvas.value.addSprite(sprite);
    

    // 保存对精灵的引用
    activeSprite.value = sprite;
  } catch (error) {
    ElMessageBox.alert(`是否跳转到 https 页面`, '错误', {
      type: 'error',
      showClose: true,
    }).then(() => {
      window.location.href = window.location.href.replace('http://', 'https://').replace(':5173', ':5174');
    });
    console.error('加载图标失败:', error);
    ElMessage.error(`加载图标失败: ${error.message || '未知错误'}`);
  }
};

// 根据blob创建适当的图像剪辑对象
const createImageClip = async (blob) => {
    let clip = null;
    if (blob.type === 'video/mp4') {
      console.log('Creating MP4Clip for video', blob);
      clip = new MP4Clip(blob.stream(), { __unsafe_hardwareAcceleration__: undefined });
      console.log('Creating MP4Clip for video2', blob.type);
    } else if (blob.type === 'image/gif') {
      clip = new ImgClip({ type: 'image/gif', stream: blob.stream() });
    } else {
      console.log('Creating ImgClip for non-GIF image');
      clip = new ImgClip(blob);
    }
    return clip;
    
};

// 保存处理后的图标
const getTransformData = async () => {
  // 截取angle为5位小数
  const result = {
    ...transformData.value,
    ...props.iconData
  }
  console.log('获取到的变换数据:', result);
  return result;
};

// 缩放控制
const zoomIn = () => {
  if (canvas.value) canvas.value.zoomIn();
};

const zoomOut = () => {
  if (canvas.value) canvas.value.zoomOut();
};

const resetView = () => {
  if (canvas.value) canvas.value.resetView();
};

// 添加重置变换的方法
const resetTransform = () => {
  if (!activeSprite.value) return;
  activeSprite.value.destroy()
  loadIcon(props.iconData.url);  
};

// 生命周期钩子
onMounted(() => {
  // 使用 nextTick 确保 DOM 已经渲染
  nextTick(initCanvas);
});

onBeforeUnmount(() => {
  // 清理资源
  if (canvas.value) {
    canvas.value = null;
  }
});

// 暴露方法给父组件
defineExpose({
  getTransformData,
  zoomIn,
  zoomOut,
  resetView,
  resetTransform
});
</script>

<style scoped>
.av-canvas-container {
  flex-direction: column;
  gap: 16px;
}

.content-wrapper {
  display: flex;
  height: 65vh;
  gap: 16px;
}

.canvas-wrapper {
  aspect-ratio: 9 / 16;
}

.transform-data-panel {
  width: 100%;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
}

.transform-data-panel h4 {
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.data-actions {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}
</style>